<?php

namespace app\common\model\mall\user;

use think\Model;
use think\Db;
use think\Cookie;
use think\Validate;

class Address extends Model
{
    // 表名
    protected $name = 'mall_user_address';
    protected $pk = 'id';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = "int";

    // 定义时间戳字段名
    protected $createTime = "createtime";
    protected $updateTime = false;
    
    // 追加属性
    protected $append = [
        'user_id_text',
        'area_ids_text',
    ];

    public function getUserIdTextAttr($value, $data)
    {
        $value = $value ? $value : $data['user_id'];
        $name = Db::name("user")->where("id","=",$value)->column("nickname");
        return $name;
    }

    public function getAreaList($pid=0)
    {
        return Db::name("area")->where("pid",$pid)->column("id,name");
    }
        
    public function getAreaIdsTextAttr($value, $data)
    {
        $value = $value ? $value : explode(",", $data['area_ids']);
        $name = Db::name("area")->where("id","in",$value)->column("name");
        return implode('', $name);
    }
    
    /**
     * 设置为默认地址
     */
    public function setDefault($uId=0){
        $user_id = ((int)$uId==0)?(int)cookie('uid'):$uId;
        $id = (int)input('post.id');
        $this->where(['id'=>['<>',$id],'user_id'=>$user_id])->setField('isDefault',0);
        $rs = $this->where("id = $id and user_id=".$user_id)->setField('isDefault',1);
        if(false !== $rs){
            return $rs;
        }else{
            throw new Exception($this->getError());
        }
    }
    /**
     * 获取默认地址
     */
    public static function getDefaultAddress($uId=0){
        $user_id = ((int)$uId==0)?(int)Cookie::get('uid'):$uId;
        $where = ['user_id'=>$user_id,'status'=>'normal'];
        $rs = self::where($where)->order('isDefault desc,id desc')->find();
        if(empty($rs))return [];
        $areaIds = explode(',',$rs['area_ids']);
        $rs['areaId2'] = $areaIds[1];
        if(!empty($areaIds)){
            $areas = Db::name('area')->where('id','in',$areaIds)->column('name');
            $rs['areaName'] = implode('',$areas);
        }
        return $rs;
    }

    /**
     *  获取地址信息
     */
    public function getById($id, $uId=0){
        $user_id = ((int)$uId==0)?(int)cookie('uid'):$uId;
        $rs = $this->get(['id'=>$id,'user_id'=>$user_id,'status'=>'normal']);
        if(empty($rs))return [];
        $tmp = explode(',',$rs['area_ids']);
        $rs['areaId2'] = $tmp[1];
        return $rs;
    }

}
